<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>闭包</title>
</head>
<script>
    var scope = "全局变量";
    (function () {
        function checkScope() {
            var scope = "局部变量";
            function f() {
                return scope;
            }
            return f();
        }
        console.log(checkScope());
    }());
    (function () {
        function checkScope() {
            var scope = "局部变量";
            function f() {
                return scope;
            }
            return f;
        }
        console.log(checkScope()());
    }());

    (function () {
        function counter() {
            var n = 0;
            return {
                count: () => n++,
                reset: () => { n = 0; },
                n: () => n
            }
        }

        var c = counter();
        var d = counter();
        console.log(c.count());
        console.log(c.n());
        console.log(c.count());
        console.log(c.n());
        console.log(d.count());
        console.log(d.n());
    }());


    (function () {
        function counter(n) {
            return {
                get count() { return n++; },
                set count(m) {
                    if (m >= n) n = m;
                    else throw Error("只能设置更大的值");
                }
            }
        }

        var c = counter(1000);
        console.log(c.count);
        console.log(c.count);
        c.count = 2000;
        console.log(c.count);
        console.log(c.count);
        //c.count = 2000;  //Error: 只能设置更大的值
    }());

    (function () {
        function constfuncs() {
            var funcs = [];
            for (var i = 0; i < 10; i++)
                funcs[i] = function () { return i; };
            return funcs;
        }
        var funcs = constfuncs();
        console.log(funcs[5]()); // What does this return?
    }());
</script>

<body>

</body>

</html>